<template>
  <div class="bgc-white">
    <div v-if="companyLst && companyLst.length > 0" class="p16">
      <a-select
        v-model="companyId"
        :options="companyLst"
        placeholder="请选择"
        :filterOption="filterOption"
        show-search
        style="width: 268px"
      />
    </div>
    <div class="flex">
      <div class="p16" style="width: 300px; flex-shrink: 0">
        <div class="flex-center-between">
          <span class="fs16 fw500">制度分类</span>
          <span
            v-show="!(currentItem && this.currentItem.level === 2)"
            style="display: inline-block; cursor: pointer"
            @click="onAddGroupItem"
          >
            <a-icon type="plus" />
          </span>
        </div>
        <div class="mt12">
          <a-input-search v-model="searchValue" placeholder="搜索分类" style="width: 268px" allowClear @change="onSearchChange" />
        </div>
        <div class="mt16">
          <a-tree
            :treeData="treeData"
            :selectedKeys="this.currentItem ? [this.currentItem.id] : null"
            :expandedKeys.sync="expandedKeys"
            :replaceFields="replaceFields"
          >
            <template slot="custom" slot-scope="node">
              <div class="flex-center-between" @click="onGroupSelected(node)">
                <a-tooltip :title="node.institutionTypeName">
                  <div class="ellipsis" style="width: 150px">
                    <span v-if="node.institutionTypeName.indexOf(searchValue) > -1">
                      {{ node.institutionTypeName.substr(0, node.institutionTypeName.indexOf(searchValue)) }}
                      <span class="tc-theme">{{ searchValue }}</span>
                      {{ node.institutionTypeName.substr(node.institutionTypeName.indexOf(searchValue) + searchValue.length) }}
                    </span>
                    <span v-else>{{ node.institutionTypeName }}</span>
                  </div>
                </a-tooltip>
                <div class="ta-right" style="width: 66px">
                  <span v-if="node.level === 2 && !node.hadInstitution" class="fs12 br4 ph4 tc-white bgc-warn mr6">未具备</span>
                  <a-icon type="setting" @click.stop="onEditGroupItem(node)" />
                </div>
              </div>
            </template>
          </a-tree>
        </div>
      </div>
      <div class="pl16" style="flex: 1; border-left: 1px solid #e8e8e8; overflow: auto; min-height: calc(100vh - 112px)">
        <ItemList v-if="treeData.length > 0 && currentItem" :currentGroup="currentItem" :companyId="companyId" />
        <div v-else class="flex-center-center" style="height: 100%">
          <a-empty :image="emptyImg">
            <template slot="description">
              <div class="mb12" style="color: rgba(159, 163, 176, 1)">抱歉，暂无制度分类</div>
              <a-button type="primary" @click="onAddGroupItem">添加制度分类</a-button>
            </template>
          </a-empty>
        </div>
      </div>
      <a-modal v-model="groupModalVisible" :title="groupModalTitle">
        <a-form :form="groupForm">
          <a-form-item label="父级分类" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
            <a-select
              v-decorator="[
                'parentId',
                {
                  initialValue: this.currentItem && this.currentItem.level === 1 ? this.currentItem.id : undefined,
                  rules: []
                }
              ]"
              :options="parentLst"
              :disabled="groupModalTitle === '编辑制度分类'"
              allowClear
              placeholder="请选择"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item label="制度分类名称" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
            <a-input
              v-decorator="['institutionTypeName', { rules: [{ required: true, message: '必须填写名称' }] }]"
              placeholder="请输入"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item label="排序" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
            <a-input
              v-decorator="[
                'sort',
                {
                  initialValue:
                    this.parentLst && this.parentLst.length > 0 ? parseInt(this.parentLst[this.parentLst.length - 1].sort) + 1 : 1,
                  rules: [
                    { required: true, message: '必须填写排序' },
                    { pattern: new RegExp(/^\+?[1-9]\d*$/), message: '只能使用正整数' }
                  ]
                }
              ]"
              placeholder="请输入"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item label="制度分类说明" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
            <a-textarea v-decorator="['institutionTypeIntroduce', { rules: [] }]" placeholder="请输入" style="width: 100%" />
          </a-form-item>
        </a-form>
        <a-space slot="footer">
          <a-button @click="groupModalVisible = false">取消</a-button>
          <a-button v-if="groupModalTitle === '编辑制度分类'" type="danger" @click="onDelGroupItem">删除</a-button>
          <a-button :loading="confirmLoadingGroup" type="primary" @click="onGroupModalOk">提交</a-button>
        </a-space>
      </a-modal>
    </div>
  </div>
</template>
<script>
import ItemList from "./list.vue";
import { mapState } from "vuex";
import ATreeMixinFunc from "@/mixins/aTree";
const ATreeMixin = ATreeMixinFunc({
  replaceFields: {
    title: "institutionTypeName",
    key: "id",
    children: "childList"
  }
});

export default {
  name: "",
  components: { ItemList },
  mixins: [ATreeMixin],
  props: {},
  data() {
    return {
      companyId: "",
      groupModalTitle: "添加制度分类",
      groupModalVisible: false,
      groupForm: this.$form.createForm(this),
      tempGroup: null,
      confirmLoadingGroup: false,
      emptyImg: require("../../admin/chanpinjieshao/empty.png")
    };
  },
  computed: {
    ...mapState(["hr"]),
    companyList() {
      return this.hr.companyList;
    },
    companyLst() {
      return this.companyList.map((item) => ({
        value: item.id,
        label: item.name
      }));
    },
    parentLst() {
      return this.treeData.map((item) => ({
        label: item.institutionTypeName,
        value: item.id,
        sort: item.sort
      }));
    }
  },
  watch: {
    companyList: {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          if (!this.companyId) {
            const temp = localStorage.getItem("zhidugongshi_companyId");
            this.companyId = temp || this.companyLst[0].value;
          }
        }
      },
      immediate: true
    },
    companyId: {
      handler(newVal) {
        if (newVal) {
          localStorage.setItem("zhidugongshi_companyId", newVal);
          this.onGroupSearchChange();
        }
      },
      immediate: true
    }
  },
  created() {},
  mounted() {},
  methods: {
    onGroupSelected(node) {
      this.currentItem = node;
      localStorage.setItem("zhidugongshiGroupId", this.currentItem.id);
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    onGroupSearchChange() {
      this.$request({
        url: `/hr/api/v1/institutionTypes/selectBySite`,
        params: {
          companyId: this.companyId
        }
      })
        .then((res) => {
          let tempId = localStorage.getItem("zhidugongshiGroupId");
          tempId = this.currentItem ? this.currentItem.id : tempId;
          this.formatData(res.data, tempId);
        })
        .catch((err) => {
          console.log("qyCompanies/selectBySite", err);
        });
    },
    onDelGroupItem() {
      this.$confirm({
        title: "删除确认",
        content: "公司删除后将无法恢复，确认要删除吗？",
        onOk: () => {
          this.$request({
            url: `/hr/api/v1/institutionTypes/${this.tempGroup.id}`,
            method: "delete"
          })
            .then(() => {
              this.$message.success("删除成功");
              this.onGroupSearchChange();
              this.groupModalVisible = false;
            })
            .catch((err) => {
              console.log("deleteReq qyCompanies", err);
            });
        }
      });
    },
    onAddGroupItem() {
      this.groupForm.resetFields();
      this.groupModalTitle = "添加制度分类";
      this.tempGroup = null;
      this.groupModalVisible = true;
    },
    onEditGroupItem(target) {
      this.tempGroup = target;
      this.groupModalTitle = "编辑制度分类";
      this.groupModalVisible = true;
      setTimeout(() => {
        this.groupForm.setFieldsValue({
          institutionTypeName: target.institutionTypeName,
          institutionTypeIntroduce: target.institutionTypeIntroduce,
          parentId: target.parentId === "0" ? undefined : target.parentId,
          sort: target.sort
        });
      }, 0);
    },
    onGroupModalOk() {
      this.groupForm.validateFields((err, values) => {
        if (!err) {
          const parentId = values.parentId || "0";
          const newValues = {
            institutionTypeName: values.institutionTypeName,
            institutionTypeIntroduce: values.institutionTypeIntroduce,
            parentId,
            sort: values.sort,
            level: parentId === "0" ? 1 : 2
          };
          this.confirmLoadingGroup = true;
          if (this.groupModalTitle === "添加制度分类") {
            this.$request({
              url: "/hr/api/v1/institutionTypes",
              method: "post",
              data: newValues
            })
              .then((res) => {
                this.$message.success("添加成功");
                this.onGroupSearchChange();
                this.groupModalVisible = false;
                this.confirmLoadingGroup = false;
              })
              .catch((err) => {
                this.confirmLoadingGroup = false;
                console.log("saveReq qyCompanies", err);
              });
          } else {
            this.$request({
              url: "/hr/api/v1/institutionTypes",
              method: "put",
              data: {
                ...newValues,
                id: this.tempGroup.id
              }
            })
              .then((res) => {
                this.$message.success("修改成功");
                this.onGroupSearchChange();
                this.groupModalVisible = false;
                this.confirmLoadingGroup = false;
              })
              .catch((err) => {
                this.confirmLoadingGroup = false;
                console.log("updateReq qyCompanies", err);
              });
          }
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.selected {
  background: var(--primary30);
  border-radius: 4px;
}
</style>
